import socket
import struct


def recv_file(sock: socket):
    fileinfo_size = struct.calcsize('!128sl')
    buf = sock.recv(fileinfo_size)

    if buf:
        filename, filesize = struct.unpack('!128sl', buf)
        fn = filename.strip(b'\00').decode('utf-8')
        print ('file new name is {0}, filesize if {1}'.format(str(fn),filesize))

        recvd_size = 0
        fp = open(r'recv_file/' + str(fn), 'wb')
        print ('start receiving...')
        while not recvd_size == filesize:
            if filesize - recvd_size > 1024:
                data = sock.recv(1024)
                recvd_size += len(data)
            else:
                data = sock.recv(filesize - recvd_size)
                recvd_size = filesize
            fp.write(data)
        fp.close()
        print ('end receive...')

if __name__ == '__main__':
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_addr = ("127.0.0.1", 8000)
    sock.connect(server_addr)

    #send_data = input("input data to send:")
    #sock.send(send_data.encode("utf-8"))

    recv_file(sock)
    sock.close()